package com.example.myvideoplayer.view;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myvideoplayer.Bean.Video;
import com.example.myvideoplayer.R;
import com.example.myvideoplayer.Utils.MyVideoAdapter;
import com.example.myvideoplayer.Utils.Untils;
import com.example.myvideoplayer.presenter.BrightnessHelper;
import com.example.myvideoplayer.presenter.VideoPresenter;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import java.util.ArrayList;

import static com.example.myvideoplayer.module.VideoPlayer.FINISH;
import static com.example.myvideoplayer.module.VideoPlayer.PAUSE;
import static com.example.myvideoplayer.module.VideoPlayer.PLAY;
import static com.example.myvideoplayer.module.VideoPlayer.SET_SEEKBAR;
import static com.example.myvideoplayer.module.VideoPlayer.SET_SURFACE_VIEW;

public class VideoPlayActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener, VideoGestureRelativeLayout.VideoGestureListener {
    private VideoPresenter videoPresenter;
    private GLSurfaceView glView;
    private ListView lv_video_list;
    private PopupWindow popupWindow;
    private View controllerView;
    private ImageView imageView_play;
    private ImageView imageView_fullscreen;
    private SeekBar seekBar;
    private TextView textView_playTime;
    private TextView textView_duration;
    private int currentPosition = 0;
    private int videoWidth = 0;
    private int videoHeight = 0;
    private int displayWidth = 0;
    private int displayHeight = 0;
    private boolean isFullScreen = false;
    private final static int SHOW_TIME = 7000;
    private final static String TAG = "video_player";

    private VideoGestureRelativeLayout ly_VG;
    private ShowChangeLayout scl;
    private AudioManager mAudioManager;
    private int maxVolume = 0;
    private int oldVolume = 0;
    private int newProgress = 0, oldProgress = 0;
    private BrightnessHelper mBrightnessHelper;
    private float brightness = 1;
    private Window mWindow;
    private WindowManager.LayoutParams mLayoutParams;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PLAY:
                    scl.setImageResource(R.drawable.pause);
                    imageView_play.setImageResource(R.drawable.pause);
                    break;
                case PAUSE:
                    scl.setImageResource(R.drawable.play);
                    imageView_play.setImageResource(R.drawable.play);
                    break;
                case SET_SEEKBAR:
                    seekBar.setMax(videoPresenter.getDuration());
                    seekBar.setProgress(msg.arg1);
                    textView_playTime.setText(Untils.formatTime(msg.arg1));
                    textView_duration.setText(Untils.formatTime(videoPresenter.getDuration()));
                    break;
                case FINISH:
                    if (popupWindow.isShowing()) {
                        handler.removeCallbacks(r);
                        popupWindow.dismiss();
                    }
                    videoPresenter.next();
                    newProgress = 0;
                    break;
                case SET_SURFACE_VIEW:
                    videoWidth = msg.arg1;
                    videoHeight = msg.arg2;
                    setSurfaceView();
                    if (isFullScreen) {
                        convertFullScreen();
                    }
                    break;
                default:
            }
        }
    };
    private Runnable r = new Runnable() {
        @Override
        public void run() {
            // 又回到了主线程
            if (popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_play);
        Log.i("2222", "playactivity:onCreate: ");
        QMUIStatusBarHelper.translucent(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        initView();
        initController();

        ly_VG = (VideoGestureRelativeLayout) findViewById(R.id.ly_VG);
        ly_VG.setVideoGestureListener(this);
        scl = (ShowChangeLayout) findViewById(R.id.scl);

        //初始化获取音量属性
        mAudioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

        //初始化亮度调节
        mBrightnessHelper = new BrightnessHelper(this);

        //下面这是设置当前APP亮度的方法配置
        mWindow = getWindow();
        mLayoutParams = mWindow.getAttributes();
        brightness = mLayoutParams.screenBrightness;
    }

    private void initView() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        displayWidth = dm.widthPixels;
        displayHeight = dm.heightPixels;
        Log.i(TAG, "initView: " + displayWidth + "   " + displayHeight);
        videoPresenter = VideoPresenter.getInstance();
        videoPresenter.setHandler(handler);
        final ArrayList<Video> videos = videoPresenter.getVideoList();
        lv_video_list = findViewById(R.id.lv_video_list);
        MyVideoAdapter myVideoAdapter = new MyVideoAdapter(videos, this);
        lv_video_list.setAdapter(myVideoAdapter);
        lv_video_list.setOnItemClickListener(this);

        glView = findViewById(R.id.sv);
        glView.setEGLContextClientVersion(2);
        GLVideoRenderer glVideoRenderer = new GLVideoRenderer(this);
        //创建renderer
        glView.setRenderer(glVideoRenderer);
        //设置renderer
        glView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);

    }

    private void initController() {
        Log.i("2222", "initController: ");
        controllerView = getLayoutInflater().inflate(
                R.layout.popwindow, null);
        controllerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 初始化popopWindow
        popupWindow = new PopupWindow(controllerView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
        popupWindow.setOutsideTouchable(false);
        imageView_play = controllerView
                .findViewById(R.id.imageView_play);
        imageView_fullscreen = controllerView
                .findViewById(R.id.imageView_fullscreen);

        seekBar = controllerView.findViewById(R.id.seekbar);

        textView_playTime = controllerView
                .findViewById(R.id.textView_playtime);
        textView_duration = controllerView
                .findViewById(R.id.textView_totaltime);
        imageView_play.setOnClickListener(this);
        imageView_fullscreen.setOnClickListener(this);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    setTextView();
                    currentPosition = progress;
                    Log.i(TAG, "onProgressChanged: " + progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                handler.removeCallbacks(r);
                videoPresenter.setSeekBarStatus(true);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                videoPresenter.seekTo(currentPosition);
                handler.postDelayed(r, SHOW_TIME);
                videoPresenter.setSeekBarStatus(false);
            }
        });
        setTextView();
        Log.i("2222", "initController:out ");
    }

    private void showController() {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            handler.removeCallbacks(r);
            int controllerHeightPixel = Untils.Dp2Px(this, 50);
            Log.i(TAG, "showController: ");
            popupWindow.showAsDropDown(glView, 0, -controllerHeightPixel);
            // 延时执行
            handler.postDelayed(r, SHOW_TIME);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_play:
                videoPresenter.playOrPause();
                break;
            case R.id.imageView_fullscreen:
                setScreen();
                break;
            default:
        }

    }

    @Override
    protected void onDestroy() {
        Log.i("3333", "onDestroy: ");
        videoPresenter.stop();
        super.onDestroy();
    }

    @Override
    protected void onPause() {

        if (popupWindow.isShowing()) {
            handler.removeCallbacks(r);
            popupWindow.dismiss();
        }
        if (videoPresenter.isPlaying()) {
            videoPresenter.playOrPause();
        }
        videoPresenter.savePosition();
        Log.i("3333", "onPause: " + currentPosition);
        super.onPause();
    }

    @Override
    protected void onRestart() {

        Log.i("1111", "onRestart: " + currentPosition);
        super.onRestart();
    }

    @Override
    protected void onPostResume() {
        //videoPresenter.play();
        super.onPostResume();
        //videoPresenter.play();
        setTextView();
        Log.i("3333", "onPostResume: ");
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Log.i(TAG, "onKeyDown:back ");
            if (popupWindow.isShowing()) {
                handler.removeCallbacks(r);
                popupWindow.dismiss();
            }
            if (isFullScreen) {
                Log.i(TAG, "onKeyDown: ");
                exitFullscreen();
            } else {
                finish();
                startActivity(new Intent(this, VideoList.class));
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setTextView() {
        textView_playTime.setText(Untils.formatTime(seekBar.getProgress()));
        seekBar.setMax(videoPresenter.getDuration());
    }

    private void setScreen() {
        popupWindow.dismiss();
        Log.i(TAG, "setScreen: " + getRequestedOrientation());
        if (isFullScreen) {
            exitFullscreen();
        } else {
            convertFullScreen();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.i(TAG, "onItemClick: " + position);
        videoPresenter.setPosition(position);
        videoPresenter.play();
        newProgress = 0;
    }

    private void convertFullScreen() {
        isFullScreen = true;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        imageView_fullscreen.setImageResource(R.drawable.fullscreen_exit);
        ViewGroup.LayoutParams lp = glView.getLayoutParams();
        if (videoWidth > videoHeight) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        lp.width = RelativeLayout.LayoutParams.MATCH_PARENT;
        lp.height = RelativeLayout.LayoutParams.MATCH_PARENT;
        glView.setLayoutParams(lp);
    }

    private void exitFullscreen() {
        isFullScreen = false;
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (videoWidth > videoHeight) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            imageView_fullscreen.setImageResource(R.drawable.fullscreen);
            glView.getLayoutParams().width = RelativeLayout.LayoutParams.MATCH_PARENT;
            glView.getLayoutParams().height = Untils.Dp2Px(this, 200);
            glView.setLayoutParams(glView.getLayoutParams());
        } else {
            setSurfaceView();
        }
    }

    public void setSurfaceView() {
        Log.i(TAG, "video:  Width:" + videoWidth + "    Height" + videoHeight);
        //Log.i(TAG,"Allview:  Width:"+dm.widthPixels+"    Height"+dm.heightPixels+"   orientation："+getRequestedOrientation());
        // Log.i(TAG,"Relayout:  Width:"+mParent.getWidth()+"    Height"+mParent.getHeight());
        //根据视频尺寸去计算-&gt;视频可以在sufaceView中放大的最大倍数。
        float max;
        max = Math.max((float) videoWidth / (float) displayWidth, (float) videoHeight / (float) Untils.Dp2Px(this, 200));
        //视频宽高分别/最大倍数值 计算出放大后的视频尺寸
        videoWidth = (int) Math.ceil((float) videoWidth / max);
        videoHeight = (int) Math.ceil((float) videoHeight / max);
        //无法直接设置视频尺寸，将计算出的视频尺寸设置到surfaceView 让视频自动填充。
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(videoWidth, videoHeight);
        params.addRule(RelativeLayout.CENTER_HORIZONTAL, ly_VG.getId());
        glView.setLayoutParams(params);
        Log.i(TAG, "params:" + "");
    }


    @Override
    public void onDown(MotionEvent e) {
        //每次按下的时候更新当前亮度和音量，还有进度
        Log.d("4444", "onDown: " + (int) ((Float.valueOf(seekBar.getProgress()) / seekBar.getMax()) * 100));
        oldProgress = (int) ((Float.valueOf(seekBar.getProgress()) / seekBar.getMax()) * 100);
        oldVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        brightness = mLayoutParams.screenBrightness;
        if (brightness == -1) {
            //一开始是默认亮度的时候，获取系统亮度，计算比例值
            brightness = mBrightnessHelper.getBrightness() / 255f;
        }
    }

    @Override
    public void onEndFF_REW(MotionEvent e) {
        makeToast("设置进度为" + newProgress);
    }

    @Override
    public void onVolumeGesture(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

        Log.d(TAG, "onVolumeGesture: oldVolume " + oldVolume);
        //单位音量的高度
        int value = ly_VG.getHeight() / maxVolume;
        int newVolume = (int) ((e1.getY() - e2.getY()) / value + oldVolume);

        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, AudioManager.FLAG_PLAY_SOUND);


//        int newVolume = oldVolume;

        Log.d(TAG, "onVolumeGesture: value" + value);

        //另外一种调音量的方法，感觉体验不好，就没采用
//        if (distanceY > value){
//            newVolume = 1 + oldVolume;
//            mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
//        }else if (distanceY < -value){
//            newVolume = oldVolume - 1;
//            mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
//        }
        Log.d(TAG, "onVolumeGesture: newVolume " + newVolume);

        //要强行转Float类型才能算出小数点，不然结果一直为0
        int volumeProgress = (int) (newVolume / Float.valueOf(maxVolume) * 100);
        if (volumeProgress >= 50) {
            scl.setImageResource(R.drawable.volume_higher_w);
        } else if (volumeProgress > 0) {
            scl.setImageResource(R.drawable.volume_lower_w);
        } else {
            scl.setImageResource(R.drawable.volume_off_w);
        }
        scl.setProgress(volumeProgress);
        scl.show();
    }

    @Override
    public void onBrightnessGesture(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        //这是直接设置系统亮度的方法
//        if (Math.abs(distanceY) > ly_VG.getHeight()/255){
//            if (distanceY > 0){
//                setBrightness(4);
//            }else {
//                setBrightness(-4);
//            }
//        }

        //下面这是设置当前APP亮度的方法
        Log.d(TAG, "onBrightnessGesture: old" + brightness);
        float newBrightness = (e1.getY() - e2.getY()) / ly_VG.getHeight();
        newBrightness += brightness;

        Log.d(TAG, "onBrightnessGesture: new" + newBrightness);
        if (newBrightness < 0) {
            newBrightness = 0;
        } else if (newBrightness > 1) {
            newBrightness = 1;
        }
        mLayoutParams.screenBrightness = newBrightness;
        mWindow.setAttributes(mLayoutParams);
        scl.setProgress((int) (newBrightness * 100));
        scl.setImageResource(R.drawable.brightness_w);
        scl.show();
    }

    //这是直接设置系统亮度的方法
    private void setBrightness(int brightness) {
        //要是有自动调节亮度，把它关掉
        mBrightnessHelper.offAutoBrightness();

        int oldBrightness = mBrightnessHelper.getBrightness();
        Log.d(TAG, "onBrightnessGesture: oldBrightness: " + oldBrightness);
        int newBrightness = oldBrightness + brightness;
        Log.d(TAG, "onBrightnessGesture: newBrightness: " + newBrightness);
        //设置亮度
        mBrightnessHelper.setSystemBrightness(newBrightness);
        //设置显示
        scl.setProgress((int) (Float.valueOf(newBrightness) / mBrightnessHelper.getMaxBrightness() * 100));
        scl.setImageResource(R.drawable.brightness_w);
        scl.show();
    }


    @Override
    public void onFF_REWGesture(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        float offset = e2.getX() - e1.getX();
        Log.d("4444", "onFF_REWGesture: offset " + offset);
        Log.d(TAG, "onFF_REWGesture: ly_VG.getWidth()" + ly_VG.getWidth());
        Log.d("4444", "onFF_REWGesture: oldpress " + oldProgress);
        //根据移动的正负决定快进还是快退
        if (offset > 0) {
            scl.setImageResource(R.drawable.ff);
            newProgress = (int) (oldProgress + offset / ly_VG.getWidth() * 100);
            if (newProgress > 100) {
                newProgress = 100;
            }
            Log.d("4444", "onFF_REWGesture: newpress" + newProgress);
        } else {
            scl.setImageResource(R.drawable.fr);
            newProgress = (int) (oldProgress + offset / ly_VG.getWidth() * 100);
            if (newProgress < 0) {
                Log.d("4444", "onFF_REWGesture: " + newProgress);
                newProgress = 0;
            }
        }
        scl.setProgress(newProgress);
        seekBar.setProgress(newProgress * (seekBar.getMax() / 100));
        videoPresenter.seekTo(newProgress * (seekBar.getMax() / 100));
        scl.show();
    }

    @Override
    public void onSingleTapGesture(MotionEvent e) {
        Log.d(TAG, "onSingleTapGesture: ");
        showController();
        makeToast("SingleTap");
    }

    @Override
    public void onDoubleTapGesture(MotionEvent e) {
        Log.d(TAG, "onDoubleTapGesture: ");
        videoPresenter.playOrPause();
        scl.showPlayOrPause();
        makeToast("DoubleTap");
    }

    private void makeToast(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }
}

